package com.jrx.mservices.ribbon.rule;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 负责均衡规则测试类
 * @author zwg
 * @date 2019-08-18 10:47
 **/

public class TestRule extends ZoneAvoidanceRule {

    private Logger logger = LoggerFactory.getLogger(TestRule.class);

    /**
     * 灰度负载状态
     * <br>通过通过这个状态设置灰度发布的负载策略，指定到特定的调用链路上
     */
    private boolean greyLoadBalance = false;

    @Override
    public Server choose(Object o) {
        //根据灰度负载状态选择服务器，可以从服务的metaInfo中找到指定的服务
        if(greyLoadBalance){
            List<Server> servers= this.getLoadBalancer().getAllServers();
            logger.info("test rule:greyLoadBalance-{}, key-{}",greyLoadBalance,o);
            return servers.get(0);
        }else{
            return super.choose(o);
        }

    }


    public boolean isGreyLoadBalance() {
        return greyLoadBalance;
    }

    public void setGreyLoadBalance(boolean greyLoadBalance) {
        this.greyLoadBalance = greyLoadBalance;
    }
}
